<template>
  <div class="filterCascader">
    <div class="filterCascader__changeBtn">
      <el-button type="text" :size="$store.getters.size" @click="handleChangeMode">
        {{ manualInputMode ? '下拉选择' : '手动输入' }}
      </el-button>
    </div>
    <el-cascader
      v-show="!manualInputMode"
      v-model="cascaderValue"
      :size="$store.getters.size"
      :options="area"
      clearable
      filterable
      v-bind="props"
      @change="handleChange"
    />
    <el-input
      v-show="manualInputMode"
      v-model="inputText"
      :size="$store.getters.size"
      clearable
      :placeholder="`xx省${props.separator}xx市`"
      v-bind="props"
      @input="handleInput"
      @blur="handleBlur"
      @keydown.native.enter="handleEnter"
    />
  </div>
</template>

<script>
import merge from 'lodash/merge'
const province = import('./province.json')
const provinceCity = import('./province-city.json')
const provinceCityDistrict = import('./province-city-district.json')
const areaArray = [province, provinceCity, provinceCityDistrict]

export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    field: {
      type: Array,
      default: () => []  
    },
    initialValue: {
      type: Array,
      default: () => []
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      area: [],
      cascaderValue: [],
      inputText: '',
      manualInputMode: false, //true：下拉选择输入，false：手动输入
      initProps: {
        placeholder: `请选择${this.title}`,
        filterable: true,
        separator: '/',
        props: {
          checkStrictly: true,
          value: 'name',
          label: 'name'
        }
      }
    }
  },
  computed: {
    props() {
      return merge({}, this.initProps, this.options)
    },
    inputValue() {
      return this.inputText.split(this.props.separator).map(i => i.trim())
    }
  },
  created() {
    areaArray[this.field.length - 1].then(res => {
      this.area = res.default
    })
    this.cascaderValue = this.initialValue
    this.inputText = this.initialValue.join(this.props.separator)
  },
  methods: {
    handleEnter() {
      this.$emit('change', this.inputValue)
    },
    handleBlur() {
      this.$emit('blur', this.inputValue)
    },
    handleChange(data) {
      this.$emit('change', data)
    },
    handleChangeMode() {
      this.manualInputMode = !this.manualInputMode
      this.cascaderValue = []
      this.inputText = ''
      this.$emit('clear')
    },
    handleInput(val) {
      this.inputText = val
        .split(/\//)
        .slice(0, this.field.length)
        .join(this.props.separator)
    }
  }
}
</script>

<style scoped lang="scss">
.filterCascader {
  width: 190px;
  position: relative;
  display: inline-flex;
  flex-direction: column;
  &__changeBtn {
    position: absolute;
    right: 30px;
    top: 1px;
    z-index: 1;
  }
}
</style>
